# encoding: UTF-8

'''
本文件中包含的是CTA模块的回测引擎，回测引擎的API和CTA引擎一致，
可以使用和实盘相同的代码进行回测。
'''

from datetime import datetime, timedelta
from collections import OrderedDict
import json
import pymongo

from base.ctaBase import *
from strategy.ctaSetting import *
from engine.ctaBacktesting import BacktestingEngine

from ctaCondiction import CondictionStrategy
from condiction.condictions import *
from database.mysqlbusiness import *

def runBacktest():
    
    # 创建回测引擎
    engine = BacktestingEngine()
    symbol = 'Rb0000'
    period = 5
    # 设置引擎的回测模式为K线
    engine.setBacktestingMode(engine.TICK_MODE)

    # 设置滑点
    engine.setSlippage(1)     # 铁矿石2跳

    # 设置回测用的数据起始日期
    engine.setStartDate('20150227')

    # 载入历史数据到引擎中
    #engine.loadHistoryData(TICK_DB_NAME, 'I1605')
    engine.loadHistoryData(TICK_DB_NAME, symbol)

    # 在引擎中创建策略对象
    #engine.initStrategy(CondictionStrategy, {'vtSymbol' : 'I1605', 'period': 1})
    engine.initStrategy(CondictionStrategy, {'vtSymbol': symbol, 'period': period})
    #增加信号条件
    RSIC = RSICondiction()
    RSIC.setParam({'RSI-PERIOD': 14, 'RSI-BUY': 30, 'RSI-SELL': 70})
    engine.strategy.addCondiction(RSIC)
    STOC = STOCondiction()
    STOC.setParam({'STO-PERIOD': 5, 'STO-KPERIOD': 3, 'STO-DPERIOD': 3, 'STO-BUY': 20, 'STO-SELL': 80})
    engine.strategy.addCondiction(STOC)
    #MALineTradeC = MALineTradeCondiction()
    #MALineTradeC.setParam({'MALine-PERIOD': 60})
    #engine.strategy.addCondiction(MALineTradeC)

    #for name, con in conds.items():
    #    engine.strategy.addCondiction(con)

    print u"开始策略CondictionStrategy, symbol=%s, condictions=[%s, %s]"
    engine.runBacktesting()

    engine.showBacktestingResult()


if __name__ == '__main__':
    runBacktest()

